<?php

namespace app\admin\command;

use think\Db;
use think\Log;
use think\Exception;
use think\console\Input;
use think\console\Output;
use WanlPay\Supports\Str;
use app\admin\model\User;
use WanlPay\Yansongda\Pay;
use think\console\Command;
use app\admin\model\wanlshop\Order;
use app\common\model\UserFinanceLog;
use app\admin\model\wanlshop\ShareOrder;

class Share extends Command
{
    protected function configure()
    {
        $this->setName('share')
            ->setDescription('分销订单打款');
    }

    protected function execute(Input $input, Output $output)
    {
        $list = Order::where('state', 'in', [4, 6])
            ->where('taketime', '<=', time() - 86400 * 7)
            ->where('finish_share', 0)
            ->where('is_share_order', 1)
            ->select();

        Log::log('get share list start...');
        $config = get_addon_config('wanlshop');
        $config = $config['agent'];
        Log::log($config);
        if ($list) {
            $ids = array_column($list, 'id');
            Log::log('count->' . count($list) . ',ids:' . implode(',', $ids));
            try {
                $shareOrder = ShareOrder::where('order_id', 'in', $ids)->select();
                if ($ids) {
                    Log::log('shareOrder count:' . count($shareOrder));
                    foreach ($shareOrder as $item) {
                        $output->writeln("switch:{$config['switch']},amount:{$item['parent_amount']}");
                        if ($config['switch'] == 'Y' && $item['parent_amount'] >= 0.1) {
                            Log::log('item:' . json_encode($item, 256));
                            $share = \app\admin\model\wanlshop\Share::withTrashed()->find($item['parent_share_id']);
                            $this->payment($item['order_sn'], $item['parent_amount'], $share['account'], $share['realname'], $output);
                        } else {
                            $this->sharePayHandle($item['id']);
                        }
                        Log::log("打款 {$item['order_sn']}");
                    }
                }
                Log::log('Db::commit');

                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                Log::log($e->getMessage() . ',line:' . $e->getLine());
            }
        }
        Log::log('get share list end...');
    }

    private function payment($order_sn, $amount, $account, $name, $output)
    {
        if ($amount < 0.1) {
            Log::log('返还金额不能小于0.1');
            return true;
        }
        $order = [
            'out_biz_no' => $order_sn,
            'trans_amount' => $amount, //todo
//            'trans_amount' => 0.1,
            'product_code' => 'TRANS_ACCOUNT_NO_PWD',
            'biz_scene' => 'DIRECT_TRANSFER',
            'payee_info' => [
                'identity' => $account,
                'identity_type' => 'ALIPAY_LOGON_ID',
                'name' => $name,
            ],
        ];
        Log::log("order_sn:$order_sn,amount:$amount,payer:$account,name:$name");
        $output->writeln("order_sn:$order_sn,amount:$amount,payer:$account,name:$name");
        Pay::alipay(self::getConfig())->transfer($order);
        return true;
    }

    private function getConfig()
    {
        $config = get_addon_config('wanlshop');
        $pay_config = [
            'app_id' => $config['sdk_alipay']['app_id'],
            'notify_url' => 'https://donghuomu.jiuhuanmall.com/api/callback',
            //'return_url' => $config['ini']['appurl'] . $config['sdk_alipay']['return_url'],
            'private_key' => $config['sdk_alipay']['private_key'],
            'log' => [
                'file' => LOG_PATH . 'wanlpay' . DS . 'alipay' . '-' . date("Y-m-d") . '.log',
                'level' => 'debug', // todo 建议生产环境等级调整为 info，开发环境为 debug
                'type' => 'single', // optional, 可选 daily.
                'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
            ],
            'http' => [
                'timeout' => 5.0,
                'connect_timeout' => 5.0
            ],
        ];
        if (isset($config['sdk_alipay']['app_cert_public_key']) && substr($config['sdk_alipay']['app_cert_public_key'], 0, 8) == '/addons/') {
            $pay_config['app_cert_public_key'] = ROOT_PATH . str_replace('/', DS, substr($config['sdk_alipay']['app_cert_public_key'], 1));
        }
        if (isset($config['sdk_alipay']['alipay_root_cert']) && substr($config['sdk_alipay']['alipay_root_cert'], 0, 8) == '/addons/') {
            $pay_config['alipay_root_cert'] = ROOT_PATH . str_replace('/', DS, substr($config['sdk_alipay']['alipay_root_cert'], 1));
        }
        if (isset($config['sdk_alipay']['ali_public_key']) && (Str::endsWith($config['sdk_alipay']['ali_public_key'], '.crt') || Str::endsWith($config['sdk_alipay']['ali_public_key'], '.pem'))) {
            $pay_config['ali_public_key'] = ROOT_PATH . str_replace('/', DS, substr($config['sdk_alipay']['ali_public_key'], 1));
        }
        return $pay_config;
    }

    private function sharePayHandle($id)
    {
        Log::log('sharePayHandle start...' . $id);
        $shareOrder = ShareOrder::find($id);
        $share = \app\admin\model\wanlshop\Share::find($shareOrder['parent_share_id']);
        $user = User::find($share['user_id']);
        $order = Order::find($shareOrder['order_id']);
        if ($order['finish_share'] == 1) {
            Log::log('finish_share=1');
            return true;
        }

        Db::startTrans();
        try {
            $after = bcadd($user['money'], $shareOrder['parent_amount'], 2);
            UserFinanceLog::create([
                'user_id' => $user['id'],
                'type' => 'money',
                'flag' => 'add',
                'value' => $shareOrder['parent_amount'],
                'before' => $user['money'],
                'after' => $after,
                'event' => 'sys',
                'rel_id' => $id,
                'remark' => "分销订单$id,佣金金额:{$shareOrder['parent_amount']}",
                'status' => 'succeed',
                'createtime' => time(),
                'updatetime' => time()
            ]);

            $user->money = $after;
            $user->save();

            $shareOrder->pay_at = date('Y-m-d H:i:s');
            $shareOrder->status = 1;
            $shareOrder->save();

            $order->finish_share = 1;
            $order->save();
            Db::commit();
            Log::log('sharePayHandle commit:' . $id);
        } catch (\Exception $e) {
            Db::rollback();
            Log::log('sharePayHandle error:' . $e->getMessage());
        }
        return true;
    }
}